package com.nchu.commondevelopmentframework.common.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nchu.commondevelopmentframework.dto.LoginUserDTO;
import com.nchu.commondevelopmentframework.entity.User;
import com.nchu.commondevelopmentframework.mapper.MenuMapper;
import com.nchu.commondevelopmentframework.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @className: UserDetailsServiceImpl
 * @description: 重写UserDetailsService类
 * @author: Li Chuanwei
 * @date: 2024/02/06 21:11
 * @Company: Copyright [日期] by [作者或个人]
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        //根据用户查询权限信息 添加到LoginUser中
        List<String> authorities = menuMapper.selectPermsByUserId(user.getUserId());

        StringJoiner stringJoiner = new StringJoiner(",", "", "");

        authorities.forEach(stringJoiner::add);

        //封装成UserDetails对象返回
        return new LoginUserDTO(
                user.getUserId(),
                user.getUserName(),
                user.getPassword(),
                user.getNickName(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(stringJoiner.toString())
        );
    }
}
